package com.mbc.common.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mbc.common.entities.CurrencyRateDetail;

public class CurrencyRateDetailDAOImpls extends DAO<CurrencyRateDetail> implements CurrencyRateDetailDAO {

	public CurrencyRateDetailDAOImpls(Connection conn)
	{
		this.conn = conn;
		this.table_name = "CurrencyRateDetail";
	}

	@Override
	public void create(CurrencyRateDetail entity) throws SQLException {
		query = "insert into " + table_name + " ( CurrencyRateDetailId, CurrencyRateId, Rate, EDateTime) values( ?, ?, ?, ?)";
		pstmt = conn.prepareStatement(query);
		int i = 1;
				pstmt.setLong(i++, entity.getCurrencyRateDetailId());
		pstmt.setLong(i++, entity.getCurrencyRateId());
		pstmt.setDouble(i++, entity.getRate());
		pstmt.setDate(i++, new java.sql.Date(entity.geteDateTime().getTime()));
		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	public void deleteByCurrencyRateId(long currencyRateId) throws SQLException {
		query = getDeleteQuery() + " where currencyrateid = " + currencyRateId;
		pstmt = conn.prepareStatement(query);
		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	protected CurrencyRateDetail readRecord(ResultSet rs) throws SQLException {
		CurrencyRateDetail l_entity = new CurrencyRateDetail();
				l_entity.setCurrencyRateDetailId(rs.getLong("CurrencyRateDetailId"));
		l_entity.setCurrencyRateId(rs.getLong("CurrencyRateId"));
		l_entity.setRate(rs.getDouble("Rate"));
		l_entity.seteDateTime(rs.getDate("EDateTime"));

		return l_entity;
	}

	@Override
	public ArrayList<CurrencyRateDetail> getDetailListByRateId(long rateId)
			throws SQLException {
		ArrayList<CurrencyRateDetail> l_list = new ArrayList<CurrencyRateDetail>();
		query = getSelectQuery() + " where currencyrateid = " + rateId;
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		while(rs.next()){
			l_list.add(readRecord(rs));
		}
		rs.close();
		pstmt.close();
		return l_list;
	}

	@Override
	public CurrencyRateDetail findLatest(long currencyRateId)
			throws SQLException {
		CurrencyRateDetail l_CurrencyRateDetail = null;
		query = "select top(1) * from " + table_name + " where currencyrateid = " + currencyRateId + " order by currencyratedetailid desc";
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		if(rs.next())
			l_CurrencyRateDetail = readRecord(rs);
		rs.close();
		pstmt.close();
		return l_CurrencyRateDetail;
	}
}
